import axios from "axios"
import decimal from "decimal.js"
/**
 * 公共方法
 */

const setPageTitle = function (title) {
	document.title = title || ''
}

export function moreDimensionalToOneDimensionalArray(array, childrenKey = 'children') {
  let newArray = []
  array.forEach(item => {
    if (item[childrenKey] instanceof Array) { // 判断是不是数组
      newArray = [...newArray, ...moreDimensionalToOneDimensionalArray(item[childrenKey])]
    }
    const one = JSON.parse(JSON.stringify(item))
    delete one[childrenKey]
    newArray.push(one)
  })
  return newArray
}

/**
 * 手机号正则验证
 */
export function mobile(mobileStr) {
  return /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/.test(mobileStr);
}

/** 
 * file转base64
*/
export function fileToBase64(file, cb) {
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function(e) {
      cb(e.target.result);
  }
  
}

/***   base64 base64*   filename 转换后的文件名*/
export const base64ToFile = (base64, filename )=> {
  let arr = base64.split(',')
  let mime = arr[0].match(/难过.*?);/)[1]
  let suffix = mime.split('/')[1]
  // 图片后缀
  let bstr = atob(arr[1]) 
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, { type: mime })
}



export default {
	setPageTitle,
	moreDimensionalToOneDimensionalArray
}
